<template>
  <div>
    <!-- 搭配上样推荐配置 -->
    <search-form
      :search-config="searchConfig"
      :label-width="150"
      @search="handleSearch"
    />
    <div v-if="btnList.length" style="margin-top:20px">
      <el-button v-for="item in btnList" :key="item.buttonId" size="mini" type="primary" @click="btnClick(item)">{{ item.buttonName }}</el-button>
      <el-button v-if="!isEdit && !showPageFlag" size="mini" type="primary" @click="handleAdd">新增</el-button>
      <el-button v-if="!isEdit && !showPageFlag" size="mini" type="primary" @click="saveNewRow">保存</el-button>
      <el-button v-if="!showPageFlag && isEdit" size="mini" type="primary" @click="saveEditRow">保存</el-button>
      <el-button v-if="!showPageFlag" size="mini" @click="cancelEdit">取消</el-button>
    </div>
    <div v-if="!btnList.length" style="margin-top:20px">
      <el-button v-if="!isEdit" size="mini" type="primary" @click="handleAdd">新增</el-button>
      <el-button v-if="showPageFlag || isEdit" size="mini" type="primary" @click="handleEdit">编辑</el-button>
      <el-button v-if="!isEdit" size="mini" type="primary" @click="handleDel">删除</el-button>
      <el-button v-if="showPageFlag" size="mini" type="primary" @click="handleImport">导入</el-button>
      <el-button v-if="showPageFlag" size="mini" type="primary" @click="handleExport">导出</el-button>
      <!-- <el-button v-if="!isEdit && !showPageFlag" size="mini" type="primary" @click="handleAdd">新增</el-button> -->
      <el-button v-if="!isEdit && !showPageFlag" size="mini" type="primary" @click="saveNewRow">保存</el-button>
      <el-button v-if="!showPageFlag && isEdit" size="mini" type="primary" @click="saveEditRow">保存</el-button>
      <el-button v-if="!showPageFlag" size="mini" @click="cancelEdit">取消</el-button>
    </div>
    <el-table
      ref="refTable"
      v-loading="tableLoading"
      element-loading-text="加载中"
      :data="tableData"
      highlight-current-row
      height="400"
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%; margin-top: 20px;border: 1px solid #EBEEF5;"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column type="selection" width="55" :selectable="selectable" />
      <el-table-column prop="modelName" label="推荐型号" min-width="80" show-overflow-tooltip>
        <template slot="header">
          <span style="color: red">*</span>推荐型号
        </template>
        <template slot-scope="scope">
          <span v-if="!scope.row.editFlag">{{ scope.row.modelName }}</span>
          <input-with-dialog
            v-else
            v-model="scope.row.model"
            :props="{label:'name',value:'code'}"
            :config="modelConfig"
            @change="modelChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="推荐品类" min-width="80" show-overflow-tooltip>
        <template slot="header">
          <span style="color: red">*</span>推荐品类
        </template>
        <template slot-scope="scope">
          <span v-if="!scope.row.editFlag">{{ scope.row.categoryName }}</span>
          <input-with-dialog
            v-else
            v-model="scope.row.category"
            :props="{label:'name',value:'code'}"
            :config="categoryConfig"
            @change="v=>reCategoryChange(v,scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="seriesName" label="推荐系列" min-width="80" show-overflow-tooltip />
      <el-table-column prop="productOrientationName" label="产品定位" min-width="80" show-overflow-tooltip />

    </el-table>
    <div class="pagination-box">
      <div v-if="showPageFlag" class="pagination-container">
        <el-pagination
          :current-page.sync="tableInfo.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="10"
          layout="sizes, prev, pager, next, slot"
          :total="allTotal === 0 ? tableInfo.total : allTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <span class="el-pagination__jump">前往
            <el-input-number
              v-model="jumpPage"
              style="width:40px"
              :controls="false"
              :min="1"
              @blur="showEnter"
              @keyup.enter.native="showEnter"
            />页</span>
        </el-pagination>
        <div v-show="tableInfo.total <= tableInfo.rows" class="pagination-info">当前显示
          <span>{{ handlePageRange(tableInfo.rows, tableInfo.currentPage) }}</span>，共
          <span class="total"> {{ tableData.length }} </span> 条记录
        </div>
        <div v-show="tableInfo.total > tableInfo.rows" class="pagination-info">当前显示
          <span>{{ handlePageRange(tableInfo.rows, tableInfo.currentPage) }}</span>，共
          <span :class="[allTotal === 0 && tableInfo.total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && tableInfo.total !== 0 ? tableInfo.total-1 +'+': allTotal }}  </span> 条记录
        </div>
      </div>
    </div>
    <div>
      <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
      <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
    </div>
  </div>
</template>

<script>
import { saveProPosition, getProPositionList, deleteProPosition } from '@/api/display/productPosition'
import { queryCategoryData } from '@/api/proConfig'
import { queryBtnList } from '@/api/basicData'

export default {
  name: 'ProductPosition',
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      showAddPage: false,
      tableLoading: false,
      isEdit: false,
      showPageFlag: true,
      activatedData: {},
      btnList: [],
      searchConfig: [
        {
          label: '推荐型号',
          prop: 'modelCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productModel/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '推荐型号',
            interfacePath: `/select-service/api/v1/productModel/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '推荐品类',
          prop: 'categoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productCategory/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '推荐品类',
            interfacePath: `/select-service/api/v1/productCategory/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' },
              { prop: 'parentCode', title: '上级品类编码' }, { prop: 'parentName', title: '上级品类名称' }],
            pageFlag: true
          }
        },
        {
          label: '推荐系列',
          prop: 'seriesCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `/select-service/api/v1/productSaleSeries/page`,
            // paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '推荐系列',
            interfacePath: `/select-service/api/v1/productSaleSeries/page`,
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        }
      ],
      tableSelected: [],
      // otherRaw: {},
      otherFilters: [],
      tableData: [],
      tableInfo: {
        currentPage: 1,
        rows: 10,
        total: undefined
      },
      jumpPage: '',
      allTotal: 0,
      modelConfig: {
        title: '型号',
        interfacePath: `/select-service/api/v1/productModel/page`,
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          }
        ]
      },
      categoryConfig: {
        title: '品类',
        interfacePath: `/select-service/api/v1/productCategory/page`,
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          },
          {
            prop: 'parentCode',
            title: '上级品类编码'
          },
          {
            prop: 'parentName',
            title: '上级品类名称'
          }
        ]
      }
    }
  },
  computed: {
    exportConfig() {
      return [
        {
          code: 'export',
          name: '产品定位配置',
          dataApi: `${process.env.VUE_APP_BASE_API}/api/v1/displayProductOrientation/export/?type=0`, // 同步数据导出api
          filtersRaw: this.otherFilters, // 符合当前查询条件的所有数据行的导出条件(当前数据查询结果对应的条件)
          selectedRows: this.tableSelected, // 当前所选中的数据行
          queryField: 'id'// 指定行导出时使用的查询字段名称
        },
        {
          code: 'exportTemplate',
          name: '产品定位配置模板',
          async: false,
          templateMethod: 'post',
          templateApi: `${process.env.VUE_APP_BASE_API}/api/v1/displayProductOrientation/export/?type=1`
        }
      ]
    },
    fileImportConfig() {
      return [{
        code: 'import',
        name: '产品定位配置',
        apiUrl: `${process.env.VUE_APP_BASE_API}/api/v1/displayProductOrientation/importExcel/?type=1`,
        selectedRows: this.tableSelected,
        paramsRaw: {},
        filtersRaw: this.otherFilters
      }]
    }
  },
  created() {
    const menuCode = this.$route.query.menuCode || 'PC0654825'
    queryBtnList(menuCode, 'default').then(res => {
      if (res.success && res.data && res.data.groovyList && (res.data.groovyList.length || res.data.groupList.length)) {
        this.btnList = [...res.data.groovyList, ...res.data.groupList]
      }
    })
    this.getTableData(1, 10, false, this.otherFilters)
  },
  methods: {
    // 获取品类
    async getCategoryData(arr) {
      const codes = '[' + arr.join(',') + ']'
      const filterRow = [{ 'id': 'code', 'property': 'code', 'operator': 'in', 'value': codes }]
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      return await queryCategoryData(dataForm).then(res => {
        if (res.success) {
          return res.data.records
        }
      })
    },
    async handleSearch(data) {
      if (!this.showPageFlag) {
        this.$message.warning('请保存数据后再进行查询')
        return
      }
      const arr = JSON.parse(JSON.stringify(data.filtersRaw))
      if (arr.length) {
        let reparentCode = ''
        const replCodeArr = arr.filter(item => item.property === 'categoryCode')
        if (replCodeArr.length) {
          const plCode = [replCodeArr[0].value]
          const pl = await this.getCategoryData(plCode)
          if (pl[0].parentCode) {
            reparentCode = pl[0].parentCode
          } else {
            reparentCode = pl[0].code
          }
        }
        arr.forEach(item => {
          if (item.property === 'categoryCode') {
            item.value = reparentCode
          }
        })
      }
      this.otherFilters = [...arr]
      this.getTableData(1, this.tableInfo.rows, false, this.otherFilters)
    },
    getTableData(page, rows, onlyCountFlag, otherFilters) {
      this.tableLoading = true
      const dataForm = new FormData()
      dataForm.append('page', page)
      dataForm.append('rows', rows)
      dataForm.append('pageFlag', true)
      dataForm.append('onlyCountFlag', onlyCountFlag)
      dataForm.append('filtersRaw', JSON.stringify(otherFilters))
      getProPositionList(dataForm).then(res => {
        if (res.success && res.data) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.tableData.forEach(item => {
              this.$set(item, 'editFlag', false)
            })
            this.tableInfo.total = res.data.total
            this.tableInfo.currentPage = res.data.page
            if (this.tableInfo.total <= page * rows) {
              this.allTotal = this.tableInfo.total
            }
          } else {
            this.allTotal = res.data.total
            this.tableInfo.total = res.data.total
            this.tableInfo.currentPage = res.data.page
          }
        }
        this.tableLoading = false
        this.showPageFlag = true
        this.isEdit = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 多选框是否可选
    selectable(row) {
      if (!this.showPageFlag) {
        if (row.id) {
          return false
        }
        return true
      }
      return true
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.tableInfo.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.tableInfo.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.tableInfo.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      if (this.addEditFlag === true) {
        this.$message.warning('当前处于修改状态，请保存或取消后再跳页')
        return false
      }
      this.jumpPage = currentPage
      this.tableInfo.currentPage = currentPage
      this.getTableData(this.tableInfo.currentPage, this.tableInfo.rows, false, this.otherFilters)
    },
    // 切换页显示条数
    handleSizeChange(size) {
      this.tableInfo.rows = size
      this.jumpToFirstPage()
      this.getTableData(this.tableInfo.currentPage, size, false, this.otherFilters)
    },

    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage

      const pageRange = `${start}-${end}`
      return pageRange
    },

    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.tableInfo.currentPage
      if (val) {
        page = val
      }
      this.getTableData(page, this.tableInfo.rows, true, this.otherFilters)
      this.$nextTick(() => {
        this.getTableData(page, this.tableInfo.rows, false, this.otherFilters)
      })
    },
    btnClick(btn) {
      switch (btn.buttonCode) {
        case 'add':
          this.handleAdd()
          break
        case 'edit':
          this.handleEdit()
          break
        case 'del':
          this.handleDel()
          break
        case 'import':
          this.handleImport()
          break
        case 'export':
          this.handleExport()
          break
        default:
          break
      }
    },
    // 新增
    handleAdd() {
      this.showPageFlag = false
      const obj = {
        modelCode: '',
        modelName: '',
        model: [],
        seriesCode: '',
        seriesName: '',
        categoryCode: '',
        categoryName: '',
        category: [],
        editFlag: true,
        productOrientationCode: '01',
        productOrientationName: '形象款'
      }
      this.tableData.unshift(obj)
    },
    // 编辑
    handleEdit() {
      if (!this.tableSelected.length) {
        this.$message.warning('请选择【编辑】项')
        return
      }
      this.tmpDataList = JSON.parse(JSON.stringify(this.tableSelected))
      this.tableSelected.forEach(item => {
        item.editFlag = true
        const model = [{ label: item.modelName, value: item.modelCode }]
        const category = [{ label: item.categoryName, value: item.categoryCode }]
        this.$set(item, 'model', model)
        this.$set(item, 'category', category)
      })
      this.isEdit = true
      this.showPageFlag = false
    },
    // 取消编辑
    cancelEdit() {
      this.getTableData(1, this.tableInfo.rows, false, this.otherFilters)
    },
    // 删除
    handleDel() {
      if (!this.tableSelected.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = this.tableSelected.filter(item => item.id)
        if (!arr.length) {
          if (this.tableSelected.length === this.tableData.length) {
            this.tableSelected = []
            this.$refs.refTable.clearSelection()
          } else {
            const tmpData = this.tableData.filter(row => {
              const index = this.tableSelected.findIndex(v => (v.categoryCode === row.categoryCode && v.modelCode === row.modelCode && v.modelCode === row.modelCode))
              return index === -1
            })
            this.tableData = tmpData
            this.tableSelected = []
            this.$refs.refTable.clearSelection()
          }
          return
        }
        const list = this.tableSelected.map(item => item.id)
        deleteProPosition(list).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData(1, 10, false, this.otherFilters)
          }
        })
      })
    },
    // 选择推荐型号
    modelChange(row) {
      if (!row.model || !row.model.length) {
        row.modelCode = ''
        row.modelName = ''
        row.seriesCode = ''
        row.seriesName = ''
        row.model = []
        return
      }
      row.modelCode = row.model[0].code
      row.modelName = row.model[0].name
      row.seriesCode = row.model[0].saleSeriesCode
      row.seriesName = row.model[0].saleSeriesName
    },
    // 选择推荐品类
    reCategoryChange(v, row) {
      if (!row.category || !row.category.length) {
        row.categoryCode = ''
        row.categoryName = ''
        row.category = []
        return
      }
      let categoryName = v[0].name
      let categoryCode = v[0].code
      // let categoryProp = { label: 'name', value: 'code' }
      if (v[0].parentCode) {
        // categoryProp = { label: 'parentName', value: 'parentCode' }
        categoryCode = v[0].parentCode
        categoryName = v[0].parentName
      }
      this.$set(row, 'category', [{ label: categoryName, value: categoryCode }])
      row.categoryCode = categoryCode
      row.categoryName = categoryName
    },
    // 刷新
    refreshTable(isInit) {
      this.$refs.matchRecommend.initTableData(isInit ? '' : 'onPage')
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    // 导入成功回调
    handleImportSuccess() {
      this.getTableData(1, this.tableInfo.rows, false, this.otherFilters)
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 新增保存
    saveNewRow() {
      if (!this.tableData.length) {
        this.$message.warning('请新增表格数据')
        return
      }
      const newData = this.tableData.filter(item => !item.id)
      if (!newData.length) {
        this.$message.warning('请添加表格数据')
        return
      }
      const flag = this.tableData.filter(item => !item.modelCode.length || !item.categoryCode.length)
      if (flag.length) {
        this.$message.warning('请完善表格数据')
        return
      }
      this.tableLoading = true
      saveProPosition(newData[0]).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.getTableData(1, 10, false, this.otherFilters)
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 编辑保存
    saveEditRow() {
      const flag1 = this.tableData.filter(item => !item.modelCode.length || !item.categoryCode.length)
      if (flag1.length) {
        this.$message.warning('请完善表格数据')
        return
      }
      this.tableLoading = true
      const newData = this.tableData.filter(item => !item.id)
      const updateData = this.tableData.filter(item => item.id && item.editFlag)
      if (newData.length > 0) {
        saveProPosition(newData[0]).then(res => {}).catch((err) => {
          this.$message.warning(err || '添加失败')
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      }
      saveProPosition(updateData[0]).then(res => {
        if (res.success) {
          this.$message.success('修改成功')
          this.getTableData(1, 10, false, this.otherFilters)
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
